/**
 * Created by nickleo on 15/3/27.
 */
function setMsgQuerySelectValue(li, btid) {
    var data = $(li).attr("data-value");
    $('#' + btid).attr("data-value", data);
    $('#' + btid).html(data + " <span class=\"caret\"></span>")
}


function queryMsgById() {

    var namesvr = $('#message-query-tab').attr("data-namesvr");
    var id = $('#message-query-input-id').val();


    var url = "/message/get_message_by_id";
    var data = {
        'namesvr': namesvr,
        'id': id
    };

    http_get(url, data, function (back) {
        drawMsgModel(id, back.message);
    });

}
function queryMsgByIdAlert(aaa) {
    var url = "/message/get_message_by_id";
    var id = $(aaa).attr("msgid");
    var data = {
        'namesvr': "",
        'id': id
    };

    http_get(url, data, function (back) {
        drawMsgModel(id, back.message);
    });

}

function drawMsgModel(id, message) {
//{"BornHost":"10.10.40.116:53042","Tags":"TAG_1","StoreHost":"192.168.251.241:10911","StoreTimestamp":"2015-03-31 12:01:56,437","BornTimestamp":"2015-03-31 12:02:04,628","QueueOffset":"51724","Topic":"FetionTopic","CommitLogOffset:":"91682936","SystemFlag":"0","QueueID":"5","ReconsumeTimes":"0","Keys":"83d27709-4c1d-c147-2f2b-b45c4cb9ba0a","Properties":"{TAGS=TAG_1, KEYS=83d27709-4c1d-c147-2f2b-b45c4cb9ba0a}"}
//    var msgBody = '  <div class="table"><p>Message ID:<span>' + id + '</span></p>' +
//        '<p>Topic:<span>' + message.Topic + '</span></p>' +
//        '<p>Tag:<span>' + message.Tags + '</span></p>' +
//        '<p>Key:<span>' + message.Keys + '</span></p>' +
//        '<p>Userproperties:<span>' + message.Properties + '</span></p>' +
//        '<p>Storetime:<span>' + message.StoreTimestamp + '</span></p>';

    var msgBody = ' <div class="table"><p>Message ID:<span>' + id + '</span></p>' +
        '<pre> ' +
        format(message) +
        '</pre>' + '</div>'

    $('#msg-content-model-body').html(msgBody);
    $('#msg-content-model').modal('show');
}


function queryMsgs() {

    var type = $('#message-query-tab').attr("data-type");
    var namesvr = $('#message-query-tab').attr("data-namesvr");
    var typeValue = $('#message-query-tab').attr("data-value");
    var key = null;
    if (type == 'msgkey') {
        key = $('#message-query-input-key').val();
    } else {

    }


    var url = "/message/get_messages";
    var data = {
        'type': type,
        'namesvr': namesvr,
        'typeValue': typeValue,
        'key': key
    };

    http_get(url, data, function (back) {
        //{"code": 200, "messages": "[{\"MessageID\":\"C0A8FBF100002A9F000000000576F878\",\"Offset\":\"51724\",\"QID\":\"5\"}]", "result": 200, "alert": "ok"}
        if (back.statusCode == 200) {
            drowMessageTables(key, $.parseJSON(back.messages));
        }
    });

}

function drowMessageTables(key, messages) {
    var tablebody = "";
    //<tr>
    //                <th style="width:400px">Message ID</th>
    //                <th>Tag</th>
    //                <th>Key</th>
    //                <th style="width:200px">Storetime</th>
    //                <th>操作</th>
    //            </tr>
    $.each(messages, function (i, msg) {
        var line = '<tr> <td><span title="' + msg.MessageID + '">' + msg.MessageID + '</span></td>' +
            '<td>' + msg.Tags + '</td>' +
            '<td>' + key + '</td>' +
            '<td width="120">' + msg.StoreTimestamp + '</td>' +
            '<td><span  class="label label-Primary" msgid="'+ msg.MessageID+'" onclick= "queryMsgByIdAlert(this)"  >查看详情</span></td></tr>';
        tablebody += line;

    });
    $("#query-message-results-body").html(tablebody);
    $("#query-message-results").show();


}

function format(txt, compress/*是否为压缩模式*/) {/* 格式化JSON源码(对象转换为JSON文本) */
    var indentChar = '    ';
    if (/^\s*$/.test(txt)) {
        alert('数据为空,无法格式化! ');
        return;
    }
    try {
        var data = eval('(' + txt + ')');
    }
    catch (e) {
        alert('数据源语法错误,格式化失败! 错误信息: ' + e.description, 'err');
        return;
    }
    ;
    var draw = [], last = false, This = this, line = compress ? '' : '\n', nodeCount = 0, maxDepth = 0;

    var notify = function (name, value, isLast, indent/*缩进*/, formObj) {
        nodeCount++;
        /*节点计数*/
        for (var i = 0, tab = ''; i < indent; i++)tab += indentChar;
        /* 缩进HTML */
        tab = compress ? '' : tab;
        /*压缩模式忽略缩进*/
        maxDepth = ++indent;
        /*缩进递增并记录*/
        if (value && value.constructor == Array) {/*处理数组*/
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + '[' + line);
            /*缩进'[' 然后换行*/
            for (var i = 0; i < value.length; i++)
                notify(i, value[i], i == value.length - 1, indent, false);
            draw.push(tab + ']' + (isLast ? line : (',' + line)));
            /*缩进']'换行,若非尾元素则添加逗号*/
        } else if (value && typeof value == 'object') {/*处理对象*/
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + '{' + line);
            /*缩进'{' 然后换行*/
            var len = 0, i = 0;
            for (var key in value)len++;
            for (var key in value)notify(key, value[key], ++i == len, indent, true);
            draw.push(tab + '}' + (isLast ? line : (',' + line)));
            /*缩进'}'换行,若非尾元素则添加逗号*/
        } else {
            if (typeof value == 'string')value = '"' + value + '"';
            draw.push(tab + (formObj ? ('"' + name + '":') : '') + value + (isLast ? '' : ',') + line);
        }
        ;
    };
    var isLast = true, indent = 0;
    notify('', data, isLast, indent, false);
    return draw.join('');
}